// server/src/controllers/contentController.ts
import { Request, Response } from 'express'
import { prisma } from '../lib/prisma'
import { sendSuccess, sendError, sendPagination } from '../utils/response'
import { AuthRequest } from '../middleware/auth'

export const getContents = async (req: Request, res: Response) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      category, 
      tag, 
      featured,
      published = 'true'
    } = req.query

    const pageNum = parseInt(page as string)
    const limitNum = parseInt(limit as string)
    const skip = (pageNum - 1) * limitNum

    const where: any = {
      isPublished: published === 'true'
    }

    if (category) {
      where.categoryId = parseInt(category as string)
    }

    if (featured) {
      where.isFeatured = featured === 'true'
    }

    if (tag) {
      where.tags = {
        some: {
          tag: {
            name: tag as string
          }
        }
      }
    }

    const [contents, total] = await Promise.all([
      prisma.content.findMany({
        where,
        include: {
          category: {
            select: {
              id: true,
              name: true,
              slug: true,
              displayName: true
            }
          },
          author: {
            select: {
              id: true,
              username: true
            }
          },
          tags: {
            include: {
              tag: true
            }
          },
          techArticle: true,
          wallpaper: true,
          game: true,
          video: true
        },
        orderBy: {
          createdAt: 'desc'
        },
        skip,
        take: limitNum
      }),
      prisma.content.count({ where })
    ])

    // 增加浏览量
    await Promise.all(
      contents.map(content => 
        prisma.content.update({
          where: { id: content.id },
          data: { viewCount: content.viewCount + 1 }
        })
      )
    )

    sendPagination(res, contents, {
      page: pageNum,
      limit: limitNum,
      total
    })
  } catch (error) {
    console.error('Get contents error:', error)
    sendError(res, '获取内容列表失败')
  }
}

export const getContent = async (req: Request, res: Response) => {
  try {
    const { id } = req.params

    const content = await prisma.content.findUnique({
      where: { id: parseInt(id) },
      include: {
        category: {
          select: {
            id: true,
            name: true,
            slug: true,
            displayName: true
          }
        },
        author: {
          select: {
            id: true,
            username: true,
            avatar: true
          }
        },
        tags: {
          include: {
            tag: true
          }
        },
        techArticle: true,
        wallpaper: true,
        game: true,
        video: true
      }
    })

    if (!content) {
      return sendError(res, '内容不存在', 404)
    }

    // 增加浏览量
    await prisma.content.update({
      where: { id: content.id },
      data: { viewCount: content.viewCount + 1 }
    })

    sendSuccess(res, { content })
  } catch (error) {
    console.error('Get content error:', error)
    sendError(res, '获取内容详情失败')
  }
}

export const getContentBySlug = async (req: Request, res: Response) => {
  try {
    const { slug } = req.params

    const content = await prisma.content.findUnique({
      where: { slug },
      include: {
        category: {
          select: {
            id: true,
            name: true,
            slug: true,
            displayName: true
          }
        },
        author: {
          select: {
            id: true,
            username: true,
            avatar: true
          }
        },
        tags: {
          include: {
            tag: true
          }
        },
        techArticle: true,
        wallpaper: true,
        game: true,
        video: true
      }
    })

    if (!content) {
      return sendError(res, '内容不存在', 404)
    }

    // 增加浏览量
    await prisma.content.update({
      where: { id: content.id },
      data: { viewCount: content.viewCount + 1 }
    })

    sendSuccess(res, { content })
  } catch (error) {
    console.error('Get content by slug error:', error)
    sendError(res, '获取内容详情失败')
  }
}

export const createContent = async (req: AuthRequest, res: Response) => {
  try {
    const {
      title,
      description,
      coverImage,
      slug,
      categoryId,
      tags,
      content, // 技术文章内容
      contentType, // 'TECH', 'WALLPAPER', 'GAME', 'VIDEO'
      // 特定类型的内容字段
      imageUrls,
      downloadLink,
      resolution,
      fileSize,
      platform,
      genre,
      score,
      officialWebsite,
      steamLink,
      videoUrl,
      videoPlatform,
      duration
    } = req.body

    // 验证必要字段
    if (!title || !slug || !categoryId || !contentType) {
      return sendError(res, '请填写所有必填字段')
    }

    // 检查 slug 是否已存在
    const existingContent = await prisma.content.findUnique({
      where: { slug }
    })

    if (existingContent) {
      return sendError(res, '该别名已存在，请使用其他别名')
    }

    // 开始事务
    const result = await prisma.$transaction(async (tx) => {
      // 创建基础内容
      const newContent = await tx.content.create({
        data: {
          title,
          description,
          coverImage,
          slug,
          categoryId: parseInt(categoryId),
          authorId: req.user!.userId,
          isPublished: false,
          isFeatured: false
        }
      })

      // 根据内容类型创建具体内容
      switch (contentType) {
        case 'TECH':
          if (!content) {
            throw new Error('技术文章内容不能为空')
          }
          await tx.techArticle.create({
            data: {
              id: newContent.id,
              content,
              toc: JSON.stringify([]) // 可以后续生成目录
            }
          })
          break

        case 'WALLPAPER':
          if (!imageUrls) {
            throw new Error('壁纸图片不能为空')
          }
          await tx.wallpaper.create({
            data: {
              id: newContent.id,
              imageUrls: JSON.stringify(imageUrls),
              downloadLink,
              resolution,
              fileSize
            }
          })
          break

        case 'GAME':
          await tx.game.create({
            data: {
              id: newContent.id,
              platform,
              genre,
              score: score ? parseFloat(score) : null,
              officialWebsite,
              steamLink
            }
          })
          break

        case 'VIDEO':
          if (!videoUrl) {
            throw new Error('视频链接不能为空')
          }
          await tx.video.create({
            data: {
              id: newContent.id,
              videoUrl,
              videoPlatform,
              duration
            }
          })
          break

        default:
          throw new Error('不支持的内容类型')
      }

      // 处理标签
      if (tags && Array.isArray(tags)) {
        for (const tagName of tags) {
          let tag = await tx.tag.findUnique({
            where: { name: tagName }
          })

          if (!tag) {
            tag = await tx.tag.create({
              data: { name: tagName }
            })
          }

          await tx.contentTag.create({
            data: {
              contentId: newContent.id,
              tagId: tag.id
            }
          })
        }
      }

      return newContent
    })

    // 获取完整的内容信息返回
    const createdContent = await prisma.content.findUnique({
      where: { id: result.id },
      include: {
        category: true,
        author: {
          select: {
            id: true,
            username: true
          }
        },
        tags: {
          include: {
            tag: true
          }
        },
        techArticle: true,
        wallpaper: true,
        game: true,
        video: true
      }
    })

    sendSuccess(res, { content: createdContent }, '内容创建成功')
  } catch (error) {
    console.error('Create content error:', error)
    sendError(res, error instanceof Error ? error.message : '内容创建失败')
  }
}

export const updateContent = async (req: AuthRequest, res: Response) => {
  try {
    const { id } = req.params
    const updateData = req.body

    // 检查内容是否存在
    const existingContent = await prisma.content.findUnique({
      where: { id: parseInt(id) }
    })

    if (!existingContent) {
      return sendError(res, '内容不存在', 404)
    }

    // 更新内容
    const updatedContent = await prisma.content.update({
      where: { id: parseInt(id) },
      data: {
        title: updateData.title,
        description: updateData.description,
        coverImage: updateData.coverImage,
        categoryId: updateData.categoryId ? parseInt(updateData.categoryId) : undefined,
        isPublished: updateData.isPublished,
        isFeatured: updateData.isFeatured
      },
      include: {
        category: true,
        author: {
          select: {
            id: true,
            username: true
          }
        },
        tags: {
          include: {
            tag: true
          }
        }
      }
    })

    sendSuccess(res, { content: updatedContent }, '内容更新成功')
  } catch (error) {
    console.error('Update content error:', error)
    sendError(res, '内容更新失败')
  }
}

export const deleteContent = async (req: AuthRequest, res: Response) => {
  try {
    const { id } = req.params

    // 检查内容是否存在
    const existingContent = await prisma.content.findUnique({
      where: { id: parseInt(id) }
    })

    if (!existingContent) {
      return sendError(res, '内容不存在', 404)
    }

    // 删除内容（由于设置了级联删除，关联的特定类型内容也会被删除）
    await prisma.content.delete({
      where: { id: parseInt(id) }
    })

    sendSuccess(res, null, '内容删除成功')
  } catch (error) {
    console.error('Delete content error:', error)
    sendError(res, '内容删除失败')
  }
}